import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

typedef void onFocusChange(bool hasFocus);
typedef void onClick();

class TvWidget extends StatefulWidget {
  // const TvWidget({super.key});
  TvWidget(
      {Key? key,
      required this.child,
      required this.focusChange,
      required this.onclick,
      required this.decoration,
      this.hasDecoration = true,
      this.requestFocus = false})
      : super(key: key);

  Widget child;
  onFocusChange focusChange;
  onClick onclick;
  bool requestFocus;
  BoxDecoration decoration;
  bool hasDecoration;

  @override
  State<TvWidget> createState() => _TvWidgetState();
}

class _TvWidgetState extends State<TvWidget> {
  late FocusNode _focusNode;
  bool init = false;
  var default_decoration = BoxDecoration(
      border: Border.all(width: 3.w, color: Colors.deepOrange),
      borderRadius: BorderRadius.all(
        Radius.circular(5.w),
      ));
  var decoration = null;

  @override
  void initState() {
    super.initState();
    _focusNode = FocusNode();
    _focusNode.addListener(() {
      if (widget.focusChange != null) {
        widget.focusChange(_focusNode.hasFocus);
      }
      if (_focusNode.hasFocus) {
        setState(() {
          if (widget.hasDecoration) {
            decoration = widget.decoration ?? default_decoration;
          }
        });
      } else {
        setState(() {
          decoration = null;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    if (widget.requestFocus && !init) {
      FocusScope.of(context).requestFocus(_focusNode);
      init = true;
    }

    return RawKeyboardListener(
      focusNode: _focusNode,
      onKey: (event) {
        if (event is RawKeyDownEvent && event.data is RawKeyEventDataAndroid) {
          if (event is RawKeyDownEvent) {
            // 处理键盘事件，例如上下左右切换焦点
            if (event.logicalKey == LogicalKeyboardKey.arrowUp) {
              FocusScope.of(context).focusInDirection(TraversalDirection.up);
            } else if (event.logicalKey == LogicalKeyboardKey.arrowDown) {
              FocusScope.of(context).focusInDirection(TraversalDirection.down);
            } else if (event.logicalKey == LogicalKeyboardKey.arrowLeft) {
              FocusScope.of(context).focusInDirection(TraversalDirection.left);
            } else if (event.logicalKey == LogicalKeyboardKey.arrowRight) {
              FocusScope.of(context).focusInDirection(TraversalDirection.right);
            } else if (event.logicalKey == LogicalKeyboardKey.enter) {
              //是否按下了确定键
              widget.onclick();
            }
          }
        }
      },
      child: Container(
        margin: EdgeInsets.all(8.w),
        decoration: decoration,
        child: widget.child,
      ),
    );
  }
}
